<template>
  <je-modal
    v-model:visible="visibleModule"
    width="460px"
    :title="$t('keyStrategyAdjustmentModal.title')"
    class="modal-key-strategy-adjustment"
    height="auto"
    :resize="false"
    :maximizable="false"
    :ok-button="addModule"
    cancel-button
    @close="cancelModal"
  >
    <je-form layout="vertical" :model="modelRef">
      <je-form-item
        :label="$t('keyStrategyAdjustmentModal.typeLabel')"
        name="RESOURCETABLE_KEY_GENERATOR_TYPE"
      >
        <je-radio-group
          v-model:value="modelRef.RESOURCETABLE_KEY_GENERATOR_TYPE"
          wrap
          :options="KEY_GENERATOR_TYPE"
          @change="onChangeType"
        />
      </je-form-item>
      <je-form-item
        v-if="stateData.sequence"
        label-align="top"
        :label="$t('keyStrategyAdjustmentModal.sequenceNameLabel')"
        name="RESOURCETABLE_INCREMENTER_NAME"
        v-bind="validateInfos.RESOURCETABLE_INCREMENTER_NAME"
      >
        <je-input v-model:value="modelRef.RESOURCETABLE_INCREMENTER_NAME" />
      </je-form-item>
      <je-form-item
        v-if="stateData.sql"
        :label="$t('keyStrategyAdjustmentModal.customSqlLabel')"
        label-align="top"
        name="RESOURCETABLE_KEY_GENERATOR_SQL"
        v-bind="validateInfos.RESOURCETABLE_KEY_GENERATOR_SQL"
      >
        <je-input v-model:value="modelRef.RESOURCETABLE_KEY_GENERATOR_SQL" />
      </je-form-item>
    </je-form>
  </je-modal>
</template>
<script>
  import { defineComponent, ref, reactive } from 'vue';
  import { Input, Modal, Form, Radio } from '@jecloud/ui';
  import { changePrimaryKeyPolicy } from '../../../api/index';
  import { verifyData, KEY_GENERATOR_TYPE } from '../../../helper/common';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'KeyStrategyAdjustment',
    components: {
      JeModal: Modal,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      JeRadioGroup: Radio.Group,
    },
    props: {
      modalData: {
        type: Object,
        default: () => {
          return {};
        },
      },
      productData: {
        type: Object,
        required: true,
        default: () => {
          return {};
        },
      },
    },
    emits: ['changeData'],
    setup(props, { emit }) {
      //保存模块数据，关闭弹窗
      const visibleModule = ref(true);
      const confirmLoading = ref(false);
      const modelRef = reactive({
        RESOURCETABLE_KEY_GENERATOR_TYPE:
          props.modalData.RESOURCETABLE_KEY_GENERATOR_TYPE || 'UUID',
        RESOURCETABLE_INCREMENTER_NAME: props.modalData.RESOURCETABLE_INCREMENTER_NAME || '',
        RESOURCETABLE_KEY_GENERATOR_SQL: props.modalData.RESOURCETABLE_KEY_GENERATOR_SQL || '',
      });
      const stateData = reactive({
        sequence: props.modalData.RESOURCETABLE_KEY_GENERATOR_TYPE == 'AUTO_INCREMENTER',
        sql: props.modalData.RESOURCETABLE_KEY_GENERATOR_TYPE == 'SQL',
      });
      const cancelModal = () => {
        visibleModule.value = false;
        emit('changeData', 'cancel');
      };
      const rulesRef = reactive({
        RESOURCETABLE_INCREMENTER_NAME:
          props.modalData.RESOURCETABLE_KEY_GENERATOR_TYPE == 'AUTO_INCREMENTER'
            ? [verifyData.required]
            : [],
        RESOURCETABLE_KEY_GENERATOR_SQL:
          props.modalData.RESOURCETABLE_KEY_GENERATOR_TYPE == 'SQL' ? [verifyData.required] : [],
      });

      const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
        onValidate: (...args) => {},
      });

      // 类型修改
      const onChangeType = () => {
        // 如果类型是自定义sql
        if (modelRef.RESOURCETABLE_KEY_GENERATOR_TYPE == 'SQL') {
          rulesRef.RESOURCETABLE_KEY_GENERATOR_SQL = [verifyData.required];
          rulesRef.RESOURCETABLE_INCREMENTER_NAME = [];
          stateData.sequence = false;
          stateData.sql = true;
          // 如果类型是序列
        } else if (modelRef.RESOURCETABLE_KEY_GENERATOR_TYPE == 'AUTO_INCREMENTER') {
          rulesRef.RESOURCETABLE_INCREMENTER_NAME = [verifyData.required];
          rulesRef.RESOURCETABLE_KEY_GENERATOR_SQL = [];
          stateData.sequence = true;
          stateData.sql = false;
        } else {
          rulesRef.RESOURCETABLE_KEY_GENERATOR_SQL = [];
          rulesRef.RESOURCETABLE_INCREMENTER_NAME = [];
          stateData.sequence = false;
          stateData.sql = false;
        }
      };

      const addModule = ({ $modal, button }) => {
        const modal = $modal,
          btn = button;
        btn.loading = true;
        validate()
          .then(() => {
            const params = {
              tableCode: 'JE_CORE_RESOURCETABLE',
              JE_CORE_RESOURCETABLE_ID: props.modalData.JE_CORE_RESOURCETABLE_ID,
              RESOURCETABLE_TABLECODE: props.modalData.RESOURCETABLE_TABLECODE,
              RESOURCETABLE_TABLENAME: props.modalData.RESOURCETABLE_TABLENAME,
            };
            Object.assign(params, modelRef);
            changePrimaryKeyPolicy(params, { pd: props.productData.productCode })
              .then((data) => {
                btn.loading = false;
                modal.close();
                Modal.notice(data.message, 'success');
                emit('changeData', 'refreshForm', data.data);
              })
              .catch((e) => {
                btn.loading = false;
                Modal.alert(e.message, 'error');
              });
          })
          .catch((error) => {
            btn.loading = false;
          });
        return false;
      };
      return {
        validateInfos,
        resetFields,
        modelRef,
        cancelModal,
        visibleModule,
        addModule,
        centered: true,
        confirmLoading,
        onChangeType,
        stateData,
        KEY_GENERATOR_TYPE,
      };
    },
  });
</script>
